import { HttpClient } from '@angular/common/http';
import { ChangeDetectionStrategy, Component, ElementRef, Input, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import videojs from 'video.js';
import Player from 'video.js/dist/types/player';

import { Api } from '../api';

@Component({
  selector: 'app-vjs-player',
  template: ` <video #target class="video-js" [width]="width" controls muted playsinline preload="none"></video> `,
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.Default,
  standalone: true,
  imports: []
})
export class VjsPlayerComponent implements OnInit, OnDestroy {
  @ViewChild('target', { static: true }) target!: ElementRef;

  // See options: https://videojs.com/guides/options
  @Input() options:
    | {
        fluid: boolean;
        aspectRatio: string;
        controls: boolean;
        autoplay: boolean;
        sources: Array<{
          src: string;
          type: string;
        }>;
      }
    | undefined;
  @Input() width: number = 720;
  @Input() record: any = {};
  player: Player | undefined;
  videoPreviewUrl: string = `${Api.BasePreviewApi}/`;
  videoSrc: string = '';
  constructor(
    private elementRef: ElementRef,
    private httpClient: HttpClient
  ) {}

  // Instantiate a Video.js player OnInit
  ngOnInit() {
    const url = this.videoPreviewUrl + this.record.id;
    // this.videoSrc = url;
    this.httpClient.get(url, { responseType: 'blob' }).subscribe(blob => {
      this.videoSrc = URL.createObjectURL(blob);
      this.options = {
        fluid: true,
        aspectRatio: '16:9',
        autoplay: true,
        controls: true,
        sources: [{ src: this.videoSrc, type: 'video/mp4' }]
      };
      this.player = videojs(this.target.nativeElement, this.options, function onPlayerReady() {});
    });
  }

  // Dispose the player OnDestroy
  ngOnDestroy() {
    if (this.player) {
      this.player.dispose();
    }
  }
}
